/**
 */
package com.dingpeikeji.quickdeer.core.modules.driver.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.beanvalidator.BeanValidators;
import com.dingpeikeji.quickdeer.core.common.config.Global;
import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.utils.DateUtils;
import com.dingpeikeji.quickdeer.core.common.utils.StringUtils;
import com.dingpeikeji.quickdeer.core.common.utils.excel.ExportExcel;
import com.dingpeikeji.quickdeer.core.common.utils.excel.ImportExcel;
import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.core.modules.driver.entity.TDrivers;
import com.dingpeikeji.quickdeer.core.modules.driver.service.TDriversService;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.realsche.entity.TRealscheVehi;
import com.dingpeikeji.quickdeer.core.modules.realsche.service.TRealscheService;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Office;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.core.modules.sys.service.OfficeService;
import com.dingpeikeji.quickdeer.core.modules.sys.service.SystemService;
import com.dingpeikeji.quickdeer.core.modules.sys.utils.UserUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 司机管理Controller
 * 
 * @author lh
 * @version 2016-05-25
 */
@Controller
@RequestMapping(value = "${adminPath}/driver/tDrivers")
public class TDriversController extends BaseController {

	@Autowired
	private TDriversService tDriversService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private TRealscheService tRealscheService;

	@ModelAttribute
	public TDrivers get(@RequestParam(required = false) String id) {
		if (StringUtils.isNotBlank(id)) {
			return tDriversService.get(id);
		} else {
			return new TDrivers();
		}
	}

	@RequiresPermissions("driver:tDrivers:view")
	@RequestMapping(value = { "list", "" })
	public String list(TDrivers tDrivers, HttpServletRequest request, HttpServletResponse response, Model model) {
		String types = request.getParameter("types");
		if (types != null && !types.equals("")) {
			tDrivers.setOffice(UserUtils.getUser().getOffice());
		}
		Page<TDrivers> page = tDriversService.findPage(new Page<TDrivers>(request, response), tDrivers);
		model.addAttribute("page", page);
		model.addAttribute("types", types);
		
		List<Map<String, Object>> mapList = Lists.newArrayList();
		Office qryOffice = new Office();
		qryOffice.setFlatType(Office.FLAT_TYPE_BUS);
		List<Office> list = officeService.findListByTerm(qryOffice);
		for (int i = 0; i < list.size(); i++) {
			Office e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentId());
			map.put("pIds", e.getParentIds());
			map.put("name", e.getName());
			mapList.add(map);
		}
		model.addAttribute("officelist", mapList);
		return "modules/driver/tDriversList";
	}
	
	@RequestMapping(value = "state")
	public String state(TDrivers tDrivers,TRealscheVehi tRealscheVehi, HttpServletRequest request, HttpServletResponse response, Model model) {
		String types = request.getParameter("types");
		tDrivers.setOffice( UserUtils.getUser().getOffice());
		TDrivers driver = tDriversService.getDriverByName(tDrivers);
		if(driver!=null){
			tRealscheVehi.setMaindriver(driver.getDrvssysid());
		}
		if(tRealscheVehi.getCreateDateQueryEnd()==null&&tRealscheVehi.getCreateDateQueryStart()==null){
			tRealscheVehi.setCreateDateQueryEnd(new Date());
			tRealscheVehi.setCreateDateQueryStart(new Date());
		}
		Page<TRealscheVehi> page = tRealscheService.findVehiPage(new Page<TRealscheVehi>(request, response), tRealscheVehi) ;
		for(int i=0;i<page.getList().size();i++){
			String t =page.getList().get(i).getMaindriver();
			try{
				page.getList().get(i).setMaindriver(tDriversService.get(t).getDrvname());
			}catch (Exception e) {
				page.getList().remove(i);
				i--;
				page.setCount(page.getCount()-1);
			}
		}
		model.addAttribute("page", page);
		model.addAttribute("tDrivers", tDrivers);
		model.addAttribute("tRealscheVehi", tRealscheVehi);
		model.addAttribute("types", types);
		return "modules/driver/tDriversState";
	}

	@RequiresPermissions("driver:tDrivers:edit")
	@RequestMapping(value = "form")
	public String form(TDrivers tDrivers, Model model, HttpServletRequest request) {
		if (tDrivers.getOffice() == null || tDrivers.getOffice().getId() == null) {
			tDrivers.setOffice(UserUtils.getUser().getOffice());
		}
		String types = request.getParameter("types");
		model.addAttribute("types", types);
		model.addAttribute("tDrivers", tDrivers);
		// 查出所有客运公司
		List<Map<String, Object>> mapList = Lists.newArrayList();
		Office qryOffice = new Office();
		qryOffice.setFlatType(Office.FLAT_TYPE_BUS);
		List<Office> list = officeService.findListByTerm(qryOffice);
		for (int i = 0; i < list.size(); i++) {
			Office e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentId());
			map.put("pIds", e.getParentIds());
			map.put("name", e.getName());
			mapList.add(map);
		}
		model.addAttribute("officelist", mapList);
		return "modules/driver/tDriversForm";
	}
	
	@RequiresPermissions("driver:tDrivers:view")
	@RequestMapping(value = "formview")
	public String formview(TDrivers tDrivers, Model model, HttpServletRequest request) {
		if (tDrivers.getOffice() == null || tDrivers.getOffice().getId() == null) {
			tDrivers.setOffice(UserUtils.getUser().getOffice());
		}
		String types = request.getParameter("types");
		model.addAttribute("types", types);
		model.addAttribute("tDrivers", tDrivers);
		// 查出所有客运公司
		List<Map<String, Object>> mapList = Lists.newArrayList();
		Office qryOffice = new Office();
		qryOffice.setFlatType(Office.FLAT_TYPE_BUS);
		List<Office> list = officeService.findListByTerm(qryOffice);
		for (int i = 0; i < list.size(); i++) {
			Office e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentId());
			map.put("pIds", e.getParentIds());
			map.put("name", e.getName());
			mapList.add(map);
		}
		model.addAttribute("officelist", mapList);
		return "modules/driver/tDriversView";
	}

	@RequiresPermissions("driver:tDrivers:edit")
	@RequestMapping(value = "save")
	public String save(TDrivers tDrivers, Model model, RedirectAttributes redirectAttributes,
			HttpServletRequest request) {
		if (!beanValidator(model, tDrivers)) {
			return form(tDrivers, model, request);
		}
		String types = request.getParameter("types");
		model.addAttribute("types", types);
		if (types.equals("1")) {
			tDrivers.setOffice(UserUtils.getUser().getOffice());
		}
		tDrivers.setCreateby(UserUtils.getUser().getId());
		tDriversService.save(tDrivers);
		addMessage(redirectAttributes, "保存司机管理成功");
		return "redirect:" + Global.getAdminPath() + "/driver/tDrivers/?repage&types=" + types + "";
	}

	@RequiresPermissions("driver:tDrivers:edit")
	@RequestMapping(value = "delete")
	public String delete(TDrivers tDrivers, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		String types = request.getParameter("types");
		tDriversService.delete(tDrivers);
		addMessage(redirectAttributes, "删除司机管理成功");
		return "redirect:" + Global.getAdminPath() + "/driver/tDrivers/?repage&types=" + types + "";
	}
	/**
	 * 导出司机数据到excel
	 * @param tDrivers
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("driver:tDrivers:view")
    @RequestMapping(value = "exportall", method=RequestMethod.POST)
    public String exportAllFile(TDrivers tDrivers, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String types = request.getParameter("types");
			if (types != null && !types.equals("")) {
				tDrivers.setOffice(UserUtils.getUser().getOffice());
			}
            String fileName = "司机数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            //Page<TDrivers> page = tDriversService.findPage(new Page<TDrivers>(request, response), tDrivers);
            List<TDrivers> list = tDriversService.findList(tDrivers);
    		ExportExcel dispose = new ExportExcel("司机数据", TDrivers.class).setDataList(list).write(response, fileName).dispose();
    		System.out.println(dispose);
    		return null;
		} catch (Exception e) {
			e.printStackTrace();
			addMessage(redirectAttributes, "导出订单数据失败！失败信息："+e.getMessage());
		}
		return "modules/driver/tDriversList";
    }
	/**
	 * 下载导入用户数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("driver:tDrivers:view")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response,HttpServletRequest request,TDrivers tDrivers, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "司机数据导入模板.xlsx";
    		tDrivers.setOffice(UserUtils.getUser().getOffice());
    		List<TDrivers> list = new ArrayList<TDrivers>();
    		Page<TDrivers> page = tDriversService.findPage(new Page<TDrivers>(request, response), tDrivers);
    		list.add(page.getList().get(0));
    		new ExportExcel("司机数据", TDrivers.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/enterlist?repage";
    }
	/**
	 * 导入用户数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<TDrivers> list = ei.getDataList(TDrivers.class);
			if (list!=null&&list.size()>0	) {
				for (TDrivers driver : list){
					driver.setOffice(UserUtils.getUser().getOffice());
					driver.setGender("男");
					driver.setCreateby(UserUtils.getUser().getId());
					tDriversService.save(driver);
					successNum++;
				}
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条司机信息");
		} catch (Exception e) {
			e.printStackTrace();
			addMessage(redirectAttributes, "导入司机信息失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/driver/tDrivers/list?repage";
    }
	/**
	 * 验证身份证号是否唯一
	 * 
	 * @param oldIdnumber
	 * @param idnumber
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("driver:tDrivers:edit")
	@RequestMapping(value = "checkIdnumber")
	public String checkIdnumber(String oldIdnumber, String idnumber) {
		if (idnumber != null && idnumber.equals(oldIdnumber)) {
			return "true";
		} else if (idnumber != null && tDriversService.getDriverByIdnumber(idnumber) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 验证手机号是否唯一
	 * 
	 * @param oldMobile
	 * @param mobile
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("driver:tDrivers:edit")
	@RequestMapping(value = "checkMobile")
	public String checkMobile(String oldMobile, String mobile) {
		if (mobile != null && mobile.equals(oldMobile)) {
			return "true";
		} else if (mobile != null && tDriversService.getDriverByMobile(mobile) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 验证驾驶证是否唯一
	 * 
	 * @param oldDrvlicno
	 * @param drvlicno
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("driver:tDrivers:edit")
	@RequestMapping(value = "checkDrvlicno")
	public String checkDrvlicno(String oldDrvlicno, String drvlicno) {
		if (drvlicno != null && drvlicno.equals(oldDrvlicno)) {
			return "true";
		} else if (drvlicno != null && tDriversService.getDriverByDrvlicno(drvlicno) == null) {
			return "true";
		}
		return "false";
	}
}
